package com.qianfeng.vhly.youshare.utils;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/2/6
 * Email: vhly@163.com
 */
public final class StreamUtil {
    // 工具类不能够继承、不能够实例化。
    private StreamUtil() {

    }

    /**
     * 关闭输入流、输出流
     *
     * @param stream Object 利用Object 来兼容 InputStream, OutputStream
     */
    public static void close(Object stream) {
        if (stream != null) {
            try {
                if (stream instanceof InputStream) {
                    ((InputStream) stream).close();
                } else if (stream instanceof OutputStream) {
                    ((OutputStream) stream).close();
                } else if (stream instanceof Reader) {
                    ((Reader) stream).close();
                } else if (stream instanceof Writer) {
                    ((Writer) stream).close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 持续读取 in 中数据，将数据直接写出到 out中
     *
     * @param in  InputStream
     * @param out OutputStream
     * @return
     */
    public static long readStream(InputStream in, OutputStream out) throws IOException {
        long ret = 0;
        if (in != null && out != null) {
            byte[] buf = new byte[128];
            int len;
            while (true){
                len = in.read(buf);
                if(len == -1){
                    break;
                }
                ret+=len;
                out.write(buf, 0, len);
            }
            buf = null;
        }
        return ret;
    }


    /**
     * 将输入流读取到字节数组中
     *
     * @param inputStream
     * @return byte[]
     * @throws IOException
     */
    public static byte[] readStream(InputStream inputStream) throws IOException {
        byte[] ret = null;
        if (inputStream != null) {
            ByteArrayOutputStream bout = null;

            bout = new ByteArrayOutputStream();

            readStream(inputStream, bout);

            // bout.toByteArray() 在返回的时候，会将内部的数组
            // 复制一份，然后返回给ret,所以这个时候，两份拷贝
            // 必须进行释放，否则产生内存问题
            ret = bout.toByteArray();

            close(bout);
            bout = null;
        }
        return ret;
    }

}
